package cn.net.autocode.platform.auth;

import cn.hutool.core.util.StrUtil;
import cn.net.autocode.core.bean.ResultT;
import cn.net.autocode.core.utils.ClientIpUtils;
import cn.net.autocode.core.utils.UserThreadLocalUtils;
import cn.net.autocode.dbManager.Dao;
import cn.net.autocode.platform.auth.service.PlatformAuthServ;
import cn.net.autocode.platform.cache.AutoCacheUtil;
import cn.net.autocode.platform.config.PlatformConfig;
import com.alibaba.fastjson2.JSONObject;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;


@Slf4j
@RestController
@RequestMapping("/mobilePlatform")
public class MobilePlatformAuth {

    private final Dao dao;

    private final AutoCacheUtil cacheUtil;

    private final PlatformAuthServ authServ;

    public MobilePlatformAuth(Dao dao, AutoCacheUtil cacheUtil, PlatformAuthServ authServ) {
        this.dao = dao;
        this.cacheUtil = cacheUtil;
        this.authServ = authServ;
    }

    /**
     * 页面登录
     */
    @PostMapping(value = "/login", produces = "application/json;charset=UTF-8")
    public ResultT login(@RequestBody JSONObject sysLoginModel, HttpServletRequest request) {
        if (sysLoginModel.isEmpty()) {
            return ResultT.fail("登录失败！");
        }

        String account = sysLoginModel.getString("account");
        String password = sysLoginModel.getString("password");

        JSONObject rs = authServ.accountLogin(account,password,"Y");

        if(rs.getIntValue("code")==1){
            String clientIp = ClientIpUtils.getIpAddr(request);
            String lastLoginOrg = rs.getString("lastLoginOrg");
            String username = rs.getString("username");
            authServ.loginLog(username,clientIp,lastLoginOrg,"Y");
            return ResultT.success(rs);
        }else if(rs.getIntValue("code")==2){
            return ResultT.success(rs);
        }else{
            return ResultT.fail(rs.getString("msg"));
        }
    }

    /**
     * 退出登录
     */
    @RequestMapping(value = "/logout",produces = "application/json;charset=UTF-8")
    @ResponseBody
    public ResultT logout(HttpServletRequest request) {
        String token = request.getHeader(PlatformConfig.mobileTokenKey);
        if (StrUtil.isBlank(token)) {
            return ResultT.success().msg("退出登录成功！");
        }
        String clientIp = ClientIpUtils.getIpAddr(request);
        cacheUtil.delToken(token,"Y");
        authServ.logoutLog(token,"Y",clientIp);
        return ResultT.success().msg("退出登录成功！");
    }


    /**
     * 页面登录
     */
    @ResponseBody
    @PostMapping(value = "/loginOrgan/{orgCode}", produces = "application/json;charset=UTF-8")
    public ResultT loginOrgan(@PathVariable("orgCode") String orgCode,HttpServletRequest request) {
        String userName = UserThreadLocalUtils.getUserName();
        String token = UserThreadLocalUtils.getToken();
        JSONObject organ = dao.queryJSON("select t1.label,t1.code from sys_organ t1,sys_organ_users t2 where t1.code=t2.org_code and t2.username=? and t2.org_code=?",userName,orgCode);
        if(organ.isEmpty()){
            cacheUtil.delToken(token,"Y");
            return ResultT.fail("您没有访问该组织的权限！");
        }else {
            JSONObject sysUser = cacheUtil.getTokenUser(token,"Y");
            sysUser.put("orgCode",orgCode);
            sysUser.put("orgName",organ.getString("label"));
            cacheUtil.setToken(token,sysUser,"Y");
            dao.executeUpdate("update sys_users set last_login_org=? where username=?",orgCode,userName);
            String clientIp = ClientIpUtils.getIpAddr(request);
            authServ.loginLog(userName,clientIp,orgCode,"Y");
            return ResultT.success();
        }
    }

    /**
     * 更改登录组织机构
     */
    @ResponseBody
    @PostMapping(value = "/changeOrgan/{orgCode}", produces = "application/json;charset=UTF-8")
    public ResultT changeOrgan(@PathVariable("orgCode") String orgCode,HttpServletRequest request) {
        String userName = UserThreadLocalUtils.getUserName();
        String token = UserThreadLocalUtils.getToken();
        JSONObject organ = dao.queryJSON("select t1.label,t1.code from sys_organ t1,sys_organ_users t2 where t1.code=t2.org_code and t2.username=? and t2.org_code=?",userName,orgCode);
        if(organ.isEmpty()){
            return ResultT.fail("您没有访问该组织的权限！");
        }else {
            JSONObject sysUser = cacheUtil.getTokenUser(token,"Y");
            sysUser.put("orgCode",orgCode);
            sysUser.put("orgName",organ.getString("label"));
            cacheUtil.setToken(token,sysUser,"Y");
            dao.executeUpdate("update sys_users set last_login_org=? where username=?",orgCode,userName);
            return ResultT.success();
        }
    }

}
